package location

import (
	"context"
	"device-admin/config/redis"
	"device-admin/internal/dal"
	"device-admin/internal/dao"
	"device-admin/internal/define"
	"strings"
	"time"

	"192.168.1.75/go-pkg/logx"
	_redis "github.com/go-redis/redis/v8"
	"github.com/qichengzx/coordtransform"
)

// GeoCacheCheck 位置坐标位置缓存检查
// 如果不存在则自动添加
func GeoCacheCheck() error {

	logx.Error(context.Background(), "GeoCacheCheck", logx.Any("0", 0))
	rdb := redis.NewDB()
	list := dao.Device{}.DeviceGeoList(context.Background(), dal.Q)
	if len(list) > 0 {
		for _, device := range list {
			merchantArr := strings.Split(device.MerchantPath, ">")
			if len(merchantArr) >= 3 && device.FloorName != "" {
				func() {
					ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
					defer cancel()
					// 转换腾讯gcj02坐标系->WGS84坐标系
					longitude, latitude := coordtransform.GCJ02toWGS84(device.Longitude, device.Latitude)
					rdb.GeoAdd(ctx,
						define.RedisGeo+merchantArr[2],
						&_redis.GeoLocation{
							Name:      device.RobotID,
							Longitude: longitude,
							Latitude:  latitude,
						},
					)
					rdb.Expire(ctx, define.RedisGeo+merchantArr[2], time.Hour)

					rdb.GeoAdd(ctx,
						define.RedisGeo,
						&_redis.GeoLocation{
							Name:      device.RobotID,
							Longitude: longitude,
							Latitude:  latitude,
						},
					)
					rdb.Expire(ctx, define.RedisGeo, time.Hour)
				}()
			}
		}
	}
	return nil
}
